#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    manager=new QNetworkAccessManager(this);
    //qDebug()<<manager->supportedSchemes();
    //QNetworkAccessManager是异步的
    connect(manager, &QNetworkAccessManager::finished, this, &MainWindow::receiveReply);
    connection=false;
    QFile file("guet_network.dat");

    if (!file.open(QIODevice::ReadOnly)) {
    }else{

        QDataStream in(&file);
        in.setVersion(QDataStream::Qt_4_3);
        in >> user;
        ui->lineEdit_name->setText(user.value("name"));
        ui->lineEdit_pwd->setText(user.value("pwd"));
        ui->comboBox_method->setCurrentText(user.value("method"));
        ui->checkBox_remenber->setChecked(true);
    }
    //启动连接测试
    {
        //构建请求对象
        QNetworkRequest request;
        request.setUrl(QUrl("http://www.baidu.com"));
        request.setHeader(QNetworkRequest::UserAgentHeader,"curl/7.68.0");
        //发送请求
        manager->get(request);
        //connection=true;
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    ui->textBrowser_result->clear();
    QString name=ui->lineEdit_name->text();
    QString pwd=ui->lineEdit_pwd->text();
    QString method=ui->comboBox_method->currentText();
//    if(ui->comboBox_type->currentText()=="GUET-WIFI"){
//        name="%2C0%2C"+name;
//    }
    if(method=="校园网"){
    }else if(method=="电信"){
        name=name+"%40telecom";
    }else if(method=="联通"){
        name=name+"%40union";
    }else if(method=="移动"){
        name=name+"%40cmcc";
    }
    QString url="";
    if(ui->comboBox_type->currentText()=="网线"){
        QDateTime time = QDateTime::currentDateTime();   //获取当前时间
        int timeT = time.toTime_t();   //将当前时间转为时间戳
        //ui->textBrowser_result->insertPlainText("time:"+QString::number(timeT)+"\n");
        QString timeTStr1=QString::number(timeT)+"000";
        QString timeTStr2=QString::number(timeT)+"030";
        url=QString("http://10.0.1.5/drcom/login?callback=dr%3&DDDDD=%1&upass=%2&0MKKey=123456&R1=0&R6=0&para=00&v6ip=&_=%4").arg(name).arg(pwd).arg(timeTStr1).arg(timeTStr2);
    }else if(ui->comboBox_type->currentText()=="GUET-WIFI"){
        if(ac.isEmpty()){
            url="http://www.baidu.com";
        }else{
            url=QString("http://10.0.1.5:801/eportal/portal/login?callback=dr1003&login_method=1")
                    +QString("&user_account=%2C0%2C%1").arg(name)
                    +QString("&user_password=%1").arg(pwd)
                    +QString("&wlan_ac_name=%1").arg(ac);
        }
    }
    ui->textBrowser_result->insertPlainText("正在尝试登陆\n");
    if(url.isEmpty()){
        ui->textBrowser_result->insertPlainText("登陆失败\n");
        return;
    }
    //构建请求对象
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::UserAgentHeader,"curl/7.68.0");

    //发送请求
    manager->get(request);
}
void MainWindow::receiveReply(QNetworkReply *reply){
    //请求方式get、post等，对应QNetworkAccessManager的Operation枚举
        //对于restful接口需要判断此枚举
        qDebug()<<"operation:"<<reply->operation();
        //路径
        qDebug()<<"url:"<<reply->url();
        //状态码
        const int status_code=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        qDebug()<<"status code:"<<status_code;
        //主动调用QNetworkReply的close或者abort也会触发finished，这时状态码为0
        //访问失败状态码也会为0
        if(status_code==0 && reply->errorString()=="Operation canceled"){
            qDebug()<<"timeout";
        }

        if(status_code==302){
            if(reply->request().url().host()=="www.baidu.com"){
                QString loc=reply->rawHeader("Location");
                //ui->textBrowser_result->insertPlainText("302 location:"+loc+"\n");
                int sstart=loc.indexOf("wlanacname=");
                if(sstart!=-1){
                    int eend=loc.indexOf("&",sstart);
                    QString ac=loc.mid(sstart,eend-sstart);
                    this->ac=ac.right(ac.length()-ac.indexOf("=")-1);
                    ui->textBrowser_result->insertPlainText("302 ac:"+this->ac+"\n");
                    ui->comboBox_type->setCurrentText("GUET-WIFI");
                }else{
                    ui->comboBox_type->setCurrentText("网线");
                }

            }
        }

        if(status_code==200&&reply->request().url().host()=="www.baidu.com"){
            if(reply->request().url().host()=="www.baidu.com"){
                ui->textBrowser_result->insertPlainText("test host:"+reply->request().url().host()+" ok\n");
                QMessageBox::information(this, "提示","网络看起来是正常的，应该不用继续登陆了");
            }
        }

        if(reply->error()!=QNetworkReply::NoError){
            //处理中的错误信息
            qDebug()<<"reply error:"<<reply->errorString();
        }else{
            if(reply->request().url().host()!="www.baidu.com"){
                const QByteArray reply_data=reply->readAll();
                ui->textBrowser_result->insertPlainText("result:"+reply_data+"\n");
                QMessageBox::information(this, "提示","服务器已响应，开网页试试能不能上网吧");
            }
        }


        reply->deleteLater();
}

void MainWindow::on_checkBox_remenber_stateChanged(int arg1)
{

    if(ui->checkBox_remenber->isChecked()){
        saveData();
    }else{
         QFile file("guet_network.dat");
         file.remove();
    }
}

void MainWindow::on_lineEdit_name_editingFinished()
{
    saveData();
}

void MainWindow::on_lineEdit_pwd_editingFinished()
{
    saveData();
}
void MainWindow::saveData(){
    if(ui->checkBox_remenber->isChecked()){
         user.insert("name",ui->lineEdit_name->text());
         user.insert("pwd",ui->lineEdit_pwd->text());
         user.insert("method",ui->comboBox_method->currentText());
         QFile file("guet_network.dat");
         if (!file.open(QIODevice::WriteOnly)) {
             return;
         }

         QDataStream out(&file);
         out.setVersion(QDataStream::Qt_4_3);
         out << user;
    }
}

void MainWindow::on_comboBox_method_currentTextChanged(const QString &arg1)
{
    saveData();
}
